package com.whpu.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whpu.common.utils.PageUtils;
import com.whpu.common.utils.Query;
import com.whpu.mall.product.dao.CategoryDao;
import com.whpu.mall.product.entity.CategoryEntity;
import com.whpu.mall.product.service.CategoryBrandRelationService;
import com.whpu.mall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService relationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 树形结构查询所有分类及其子分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1. 查出所有分类
        List<CategoryEntity> categoryList = baseMapper.selectList(null);

        //2. 拼成树形结构
        //2.1 一级分类 -> pid = 0的分类
        List<CategoryEntity> categoryParentList = categoryList.stream().
                filter(cateory -> cateory.getParentCid() == 0).
                map((menu) -> {
                    //调用方法设置其子菜单
                    menu.setChildren(getChildren(menu, categoryList));
                    return menu;
                }).
                sorted((menu1, menu2) -> {
                    //根据sort字段排序
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).
                collect(Collectors.toList());


        return categoryParentList;
    }

    /**
     * 递归查询某个菜单的所有子菜单
     *
     * @param categoryRoot 要查询的菜单
     * @param categoryList 所有菜单列表
     * @return
     */
    public List<CategoryEntity> getChildren(CategoryEntity categoryRoot, List<CategoryEntity> categoryList) {

        List<CategoryEntity> children = categoryList.stream().
                //判断是否是子菜单
                filter(categoryEntity -> categoryEntity.getParentCid().equals(categoryRoot.getCatId())). //这块一定用equals()
                map(categoryEntity -> {
                //递归查询子菜单
                    categoryEntity.setChildren(getChildren(categoryEntity, categoryList));
                    return categoryEntity;
                }).
                sorted((menu1, menu2) -> {
                    //根据sort字段排序
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).
                collect(Collectors.toList());

        return children;

    }

    /**
     * 批量删除没有子节点的节点
     * @param asList
     */
    @Override
    public void delMenusIfNotExistChildren(List<Long> asList) {
        //TODO 检查当前菜单是否有子菜单

        //逻辑删除

        baseMapper.deleteBatchIds(asList);

    }

    /**
     * 找到分组路径,如层级关系:[4,22,255]
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findGroupPath(Long catelogId) {
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);

        List<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);  //反转集合,将父id放前面

        return parentPath.toArray(new Long[parentPath.size()]); //转换


    }


    //递归查找层级关系
    public List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);  //先把当前的id放进集合
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0){ //判断父结点id
            findParentPath(categoryEntity.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 级联更新分类所有关联数据
     * @param category
     */
    @Override
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);

        if (!StringUtils.isEmpty(category.getName())){
            relationService.updateCategory(category.getCatId(),category.getName());
        }

    }

}
